//
//  SYDLocationManage.m
//  PinGJByOwnerSide
//
//  Created by lantaiyuan on 2017/9/5.
//  Copyright © 2017年 lantaiyuan. All rights reserved.
//

#import "SYDLocationManage.h"

@interface SYDLocationManage()<AMapLocationManagerDelegate, AMapSearchDelegate>

@property (nonatomic, strong) AMapSearchAPI *search;
@property (nonatomic, strong) AMapLocationManager * locationManager;
@end
@implementation SYDLocationManage

#pragma mark - Lazy

- (AMapSearchAPI *)search{
    if (!_search) {
        _search = [[AMapSearchAPI alloc] init];
        _search.delegate = self;
        //查询超时时间，单位秒，默认为20秒
        _search.timeout = 15;
    }
    return _search;
}

- (AMapLocationManager *)locationManager{
    if (!_locationManager) {
        _locationManager = [[AMapLocationManager alloc] init];
        _locationManager.delegate = self;
        
        // 带逆地理信息的一次定位（返回坐标和地址信息）
        [_locationManager setDesiredAccuracy:kCLLocationAccuracyBest];
        // 定位超时时间，最低2s，此处设置为11s
        _locationManager.locationTimeout = 2;
        // 逆地理请求超时时间，最低2s，此处设置为12s
        _locationManager.reGeocodeTimeout = 2;
        //是否允许后台定位,默认为NO
        _locationManager.allowsBackgroundLocationUpdates = YES;
        
        //连续定位是否返回逆地理信息，默认NO
        [_locationManager setLocatingWithReGeocode:YES];
    }
    return _locationManager;
}

#pragma mark - Private Methods
- (instancetype)init {
    if (self = [super init]) {
        //默认单次定位
        [self startOnceLocation];
    }
    return self;
}
//连续定位
- (void)startSerialLocation
{
    NSLog(@"开始连续定位");
    [self.locationManager startUpdatingLocation];
}
//停止连续定位
- (void)stopSerialLocation
{
    //停止定位
    [self.locationManager stopUpdatingLocation];
}
//开始单次定位
- (void)startOnceLocation{
    
    WEAKSELF
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        
        if (error) {
            NSLog(@"单次定位异常的error:%@,经纬度:---%f------%f",error,location.coordinate.latitude,location.coordinate.longitude);
        }else{
            
//            [YMSaveTool setObject:[NSString stringWithFormat:@"%f",location.coordinate.latitude] forKey:USER_LATITUDE];
//            [YMSaveTool setObject:[NSString stringWithFormat:@"%f",location.coordinate.longitude] forKey:USER_LONGITUDE];
            
            [YMSaveTool setDouble:location.coordinate.latitude forKey:USER_LATITUDE];
            [YMSaveTool setDouble:location.coordinate.longitude forKey:USER_LONGITUDE];
            
            [YMSaveTool setValue:regeocode.adcode forKey:adCode];
            [YMSaveTool setValue:regeocode.city forKey:@"currentLocationName"];
            if (regeocode) {
                //存在逆地理信息
                NSLog(@"单次定位成功,得到的城市:%@,GPS坐标:%f--%f,位置:%@--%@",regeocode.city,location.coordinate.latitude,location.coordinate.longitude,regeocode.POIName,regeocode.adcode);
                
                [YMSaveTool setValue:regeocode.POIName forKey:@"positionName"];
                [YMSaveTool setObject:regeocode.adcode forKey:adCode];
                
                if (_locationSuccessBlock) {
                    weakSelf.locationSuccessBlock(location.coordinate, regeocode.POIName);
                }
                
            }else{
                NSLog(@"单次定位失败,此刻不存在逆地理信息!");
                
                if (_locationFailedBlock) {
                    weakSelf.locationFailedBlock();
                }
            }
        }
    }];
}
// 单次定位
- (void)locationWithReGeocode:(AMapLocatingCompletionBlock)completionBlock{
    //带逆地理的单次定位
    [self.locationManager requestLocationWithReGeocode:YES completionBlock:^(CLLocation *location, AMapLocationReGeocode *regeocode, NSError *error) {
        completionBlock(location, regeocode, error);
    }];
}

// 逆地理编码
- (void)reGeocodeWithCoordinate:(CLLocationCoordinate2D)coordinate{
    
    AMapGeoPoint * location = [AMapGeoPoint locationWithLatitude:coordinate.latitude longitude:coordinate.longitude];
    
    AMapReGeocodeSearchRequest * request = [[AMapReGeocodeSearchRequest alloc] init];
    request.location = location;
    [self.search AMapReGoecodeSearch:request];
}

#pragma mark - AMapLocationManagerDelegate

- (void)amapLocationManager:(AMapLocationManager *)manager didFailWithError:(NSError *)error
{
    //定位错误
    NSLog(@"%s, amapLocationManager = %@, error = %@", __func__, [manager class], error);
    if (_locationFailedBlock) {
        _locationFailedBlock();
    }
}
- (void)amapLocationManager:(AMapLocationManager *)manager didUpdateLocation:(CLLocation *)location
{
    //定位结果
    NSLog(@"location:{lat:%f; lon:%f; accuracy:%f}", location.coordinate.latitude, location.coordinate.longitude, location.horizontalAccuracy);
    [self stopSerialLocation];
    
    [self reGeocodeWithCoordinate:location.coordinate];
}

#pragma mark - AMapSearchDelegate

- (void)onReGeocodeSearchDone:(AMapReGeocodeSearchRequest *)request response:(AMapReGeocodeSearchResponse *)response{
    if (response.regeocode != nil) {
        CLLocationCoordinate2D coordinate = CLLocationCoordinate2DMake(request.location.latitude, request.location.longitude);
        
        NSString * province = response.regeocode.addressComponent.province == nil ? @"" : response.regeocode.addressComponent.province;
        NSString * city = response.regeocode.addressComponent.city == nil ? @"" : response.regeocode.addressComponent.city;
        NSString * district = response.regeocode.addressComponent.district == nil ? @"" : response.regeocode.addressComponent.district;
        NSString * street = response.regeocode.addressComponent.streetNumber.street == nil ? @"" : response.regeocode.addressComponent.streetNumber.street;
        NSString * number = response.regeocode.addressComponent.streetNumber.number == nil ? @"" : response.regeocode.addressComponent.streetNumber.number;
        NSString * building = response.regeocode.addressComponent.building == nil ? @"" : response.regeocode.addressComponent.building;
        
        NSString * address = [NSString stringWithFormat:@"%@%@%@%@%@%@",province,city,district,street,number,building];
        //保存经纬度,逆地理编码地址
        if (_locationSuccessBlock) {
            _locationSuccessBlock(coordinate,address);
        }
    }
}
+ (BOOL)isLocationServiceOpen {
    if ([ CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied) {
        return NO;
    } else
        return YES;
}
@end






